import crypto from 'crypto';

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId;
  this.sessionKey = sessionKey;
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  return new Promise((resolve, reject) => {
    // base64 decode
    const sessionKey = Buffer.from(this.sessionKey, 'base64');
    encryptedData = Buffer.from(encryptedData, 'base64');
    iv = Buffer.from(iv, 'base64');

    try {
      // 解密
      const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
      // 设置自动 padding 为 true，删除填充补位
      decipher.setAutoPadding(true);
      let decoded = decipher.update(encryptedData, 'binary', 'utf8');
      let parseDecoded = null;
      decoded += decipher.final('utf8');
      parseDecoded = JSON.parse(decoded);
      if (parseDecoded.watermark.appid !== this.appId) {
        reject('Illegal Buffer');
      } else {
        resolve(decoded);
      }
    } catch (err) {
      reject('Illegal Buffer');
    }
  });
};

export default WXBizDataCrypt;
